package com.gjm.demo.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Slf4j
@Aspect
//@Component
public class TimeRecordAspect {

//    /**
//     * 记录 controller 下的方法运行的时间
//     * @param pjp
//     * @return
//     * @throws Throwable
//     */
//    @Around("execution(* com.gjm.demo.controller.*.*(..))")
//    public Object timeRecord(ProceedingJoinPoint pjp) throws Throwable {
//        log.info("开始记录时间");
//
//        long begin = System.currentTimeMillis();
//
//        Object proceed = pjp.proceed();
//
//        long end = System.currentTimeMillis();
//
//        log.info("方法耗时: " + (end - begin) + "ms");
//
//        log.info("记录时间结束");
//        return proceed;
//    }

    @Pointcut("execution(* com.gjm.demo.controller.*.*(..))")
    public void pt() {}

    @Around("pt()")
    public Object timeRecord(ProceedingJoinPoint pjp) throws Throwable {
        log.info("do before");

        long begin = System.currentTimeMillis();

        Object proceed = null;

        try {
            proceed = pjp.proceed();
        } catch (Throwable e){
            log.info("do afterThrowing");
            return proceed;
        }

        long end = System.currentTimeMillis();

        log.info("方法耗时: " + (end - begin) + "ms");

        log.info("do after");

        return proceed;
    }

    @Before("pt()")
    public void doBefore() {
        log.info("do before");
    }

    @After("pt()")
    public void doAfter() {
        log.info("do after");
    }

    @AfterReturning("pt()")
    public void doAfterReturning() {
        log.info("do afterReturning");
    }

    @AfterThrowing("pt()")
    public void doAfterThrowing() {
        log.info("do afterThrowing");
    }
}
